package com.sunfeng.commonlib.message;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import de.greenrobot.event.EventBus;

/**
 * 通用 Message管理类
 * Created by wutiaorong on 2017/10/19.
 */

public class CommonMessageManager {
    private CommonMessageManager() {
    }

    private static class SingletonHolder {
        private static final CommonMessageManager INSTANCE = new CommonMessageManager();
    }

    private ConcurrentHashMap<CommonMessage.Type, Object> mUnreadedDialogMsg = new ConcurrentHashMap<>();// 同时多条消息put和remove会引起同步问题，所以使用ConcurrentHashMap

    public void unreadMsg(CommonMessage.Type msgType, Object object) {
        mUnreadedDialogMsg.put(msgType, object);
    }

    public void readMsg(CommonMessage.Type msgType) {
        mUnreadedDialogMsg.remove(msgType);
    }

    public void rePushCacheMsg() {
        if (mUnreadedDialogMsg.size() > 0) {
            for (Map.Entry<CommonMessage.Type, Object> entry : mUnreadedDialogMsg.entrySet()) {
                if (null != entry) {
                    notifyUnreadWhat(entry.getKey(), entry.getValue());
                }
            }
        }
    }

    public static CommonMessageManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void registerObserver(Object subscriber) {
        EventBus.getDefault().register(subscriber);
    }

    public void unRegisterObserver(Object subscriber) {
        EventBus.getDefault().unregister(subscriber);
    }

    public void notify(CommonMessage.Type type) {
        EventBus.getDefault().post(new CommonMessage(type, ""));
    }

    public void notifyMsg(CommonMessage.Type type, String msg) {
        EventBus.getDefault().post(new CommonMessage(type, msg));
    }

    public void notifyWhat(CommonMessage.Type type, Object what) {
        EventBus.getDefault().post(new CommonMessage(type, "", what));
    }

    public void notifyUnreadWhat(CommonMessage.Type type, Object what) {
        unreadMsg(type, what);
        EventBus.getDefault().post(new CommonMessage(type, "", what));
    }

    public void notifyWhatMsg(CommonMessage.Type type, String msg, Object what) {
        EventBus.getDefault().post(new CommonMessage(type, msg, what));
    }

    public void clearUnreadMsg() {
        mUnreadedDialogMsg.clear();
    }
}